#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <unordered_map>

#include "log.hpp"

Log lg;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};

uint16_t defaultport = 8080;
std::string defaultip = "0.0.0.0";
const int size = 1024;

//服务端类
class UdpServer
{
public:
    //构造
    UdpServer(const uint16_t& port = defaultport, const std::string& ip = defaultip)
    : sockfd_(-1)
    , port_(port)
    , ip_(ip)
    {}

    //初始化
    void Init()
    {
        //创建套接字
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0); 
        if(sockfd_ < 0)
        {
            lg(Fatal, "socket create error, sockfd: %d", sockfd_);
            exit(SOCKET_ERR);
        }
        lg(Info, "socket create success, sockfd: %d", sockfd_);

        //绑定
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_); //保证网络字节序
        local.sin_addr.s_addr = inet_addr(ip_.c_str()); 
        //local.sin_addr.s_addr = htonl(INADDR_ANY); //ip另一种写法

        if(bind(sockfd_, (const struct sockaddr*)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success, errno: %d, err string: %s", errno, strerror(errno));
    }

    void CheckUser(const struct sockaddr_in &client, const std::string clientip, uint16_t clientport)
    {
        //在客户表里查找ip，如果找不到就添加客户信息
        auto iter = online_user_.find(clientip);
        if(iter == online_user_.end())
        {
            online_user_.insert({clientip, client});
            std::cout << "[" << clientip << ":" << clientport << "] add to online user." << std::endl;
        }
    }

    void Broadcast(const std::string& message)
    {
        //群发给客户
        for(const auto& user : online_user_)
        {
            //发送
            socklen_t len = sizeof(user.second);
            sendto(sockfd_, message.c_str(), message.size(), 0, (struct sockaddr*)&(user.second), len);
        }
    }

    //运行
    void Run() 
    {
        char inbuffer[size]; //接收缓冲区
        while(true)
        {
            //接收
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(sockfd_, inbuffer, sizeof(inbuffer)-1, 0, (struct sockaddr*)&client, &len);
            if(n < 0)
            {
                lg(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }
            inbuffer[size] = 0;
            
            //提取客户信息
            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);

            //添加客户信息
            CheckUser(client, clientip, clientport);

            //群发给客户, 构造字符串 [clientip:clientport]#inbuffer
            std::string message = "[";
            message += clientip;
            message += ":";
            message += std::to_string(clientport);
            message += "]# ";
            message += inbuffer;
            Broadcast(message);
        }
    }

    //析构
    ~UdpServer()
    {
        if(sockfd_ >= 0) 
        {
            close(sockfd_);
            sockfd_ = -1;
        }
    }

private:
    int sockfd_;     // 网络文件描述符
    std::string ip_; // 任意地址bind 0
    uint16_t port_;  // 表明服务器进程的端口号
    std::unordered_map<std::string, struct sockaddr_in> online_user_; //成员列表，ip和socket结构体的映射
};